#!/bin/sh

set -e

clean_up () {
    ARG=$?
    pkill -9 -f  "python3 -m http.server ${http_port}"
    virsh -c qemu:///session destroy "fedora-35-127.0.0.2-${ssh_port}"
    virsh -c qemu:///session undefine "fedora-35-127.0.0.2-${ssh_port}"
    exit $ARG
}

trap clean_up INT TERM EXIT

# determine http server forward port
http_port=8000
while netstat -vatn | grep $http_port; do
    http_port=$((http_port+1))
    echo 'Trying http port: ' $http_port
done

# determine ssh forward port
ssh_port=22000
while netstat -vatn | grep $ssh_port; do
    ssh_port=$((ssh_port+1))
    echo 'Trying ssh port: ' $ssh_port
done

# determine cockpit forward port
cockpit_port=9091
while netstat -vatn | grep $cockpit_port; do
    cockpit_port=$((cockpit_port+1))
    echo 'Trying cockpit port: ' $cockpit_port
done

echo "Host http server port: $http_port"
echo "Host ssh port: $ssh_port"
echo "Host cockpit port: $cockpit_port"

cd ../../

# FIXME boot.iso on rawhide does not currently contain the new cockpit dependencies
# This will change once we include this changes upstream and start building boot.iso with the new dependencies
# Then we can safely remove this workaround
test ! -e cockpit-ws*.rpm && curl -LO https://kojipkgs.fedoraproject.org//packages/cockpit/259/1.fc35/x86_64/cockpit-ws-259-1.fc35.x86_64.rpm
test ! -e cockpit-bridge*.rpm && curl -LO https://kojipkgs.fedoraproject.org//packages/cockpit/259/1.fc35/x86_64/cockpit-bridge-259-1.fc35.x86_64.rpm

scripts/makeupdates --add "$RPM_PATH"/anaconda-*.rpm --add cockpit-*.rpm
python3 -m http.server "${http_port}" &
cd ui/webui/

WAIT=""
if ! test -z "$VM_ONLY"; then
    WAIT="--wait -1"
fi

# Run the test VM
eval virt-install --connect qemu:///session \
        --quiet --name "fedora-35-127.0.0.2-${ssh_port}" \
        "$WAIT" \
        --os-variant fedora-rawhide \
        --memory 2048 \
        --noautoconsole \
        --graphics vnc,listen=127.0.0.2 \
        --extra-args="'inst.sshd inst.nokill inst.updates=http://10.0.2.2:${http_port}/updates.img'" \
        --network none \
        --qemu-commandline="'-netdev user,id=hostnet0,hostfwd=tcp:127.0.0.2:${ssh_port}-:22,hostfwd=tcp:127.0.0.2:${cockpit_port}-:9090 -device virtio-net-pci,netdev=hostnet0,id=net0'" \
        --initrd-inject "$(pwd)"/test/ks.cfg --extra-args "inst.ks=file:/ks.cfg" \
        --disk size=10,format=qcow2 --location "$1"

if test -z "$VM_ONLY"; then
    until curl --silent -o /dev/null --head --fail "http://127.0.0.2:${cockpit_port}/cockpit/@localhost/anaconda-webui/index.html"; do
        echo 'Waiting for anaconda UI to show up...'
        sleep 5
    done

    TEST_ALLOW_NOLOGIN=true test/common/run-tests --jobs 1 --machine "127.0.0.2:${ssh_port}" --browser "127.0.0.2:${cockpit_port}"
fi
